import sys
parent_dir = "../pygl"
sys.path.append(parent_dir)
import OpenGL.GL as gl
import glm
import imgui
import numpy as np
from common.app_v1 import App
import pygl

class TriangleApp(App):
    # 初始化着色器，vao vbo等
    def setupVertex(self) -> None:
        self.program = pygl.ProgramVF("basic/shaders/triangle.vs", 
                                      "basic/shaders/triangle.fs")
        vertices = np.array([
            # position          # color
            0.0, 0.25, 0.0,     1.0, 0.0, 0.0,
            0.25, -0.25, 0.0,   0.0, 1.0, 0.0,
            -0.25, -0.25, 0.0,  0.0, 0.0, 1.0
        ], dtype=gl.GLfloat)

        self.vao = pygl.VertexArrayObject()
        self.vbo = pygl.VertexBufferObject(vertices)
        
        binding_point = 0
        self.vao.setVertexBuffer(self.vbo, binding_point, 0, 
                                6 * gl.sizeof(gl.GLfloat))

        attribute_position = pygl.VertexAttribute("position", 0, 
                                3, gl.GL_FLOAT, False, 0)
        attribute_color = pygl.VertexAttribute("color",1, 3, 
                                gl.GL_FLOAT, False, 3 * gl.sizeof(gl.GLfloat))
        self.vao.setVertexAttribute(binding_point, attribute_position)
        self.vao.setVertexAttribute(binding_point, attribute_color)

        self.color = (1.0, 1.0, 1.0)
        self.x_offset = 0.0
        self.x_increment = 0.0002

    # 配置imgui界面元素
    def showImGui(self)->None:
        imgui.begin("设置")
        _, self.color = imgui.color_edit3("光照颜色", self.color[0], 
                                    self.color[1], self.color[2])
        _, color = imgui.color_edit3("背景颜色", self.background_color.x, 
                                     self.background_color.y, 
                                     self.background_color.z)
        self.background_color = glm.vec4(color[0], color[1], color[2], 1.0)
        imgui.end()       

    # 渲染图形
    def render(self) -> None:
        gl.glClearNamedFramebufferfv(0, gl.GL_COLOR, 0, self.background_color.to_tuple())
        self.program.use()
        self.x_offset += self.x_increment
        if self.x_offset < -0.7:
            self.x_increment = -self.x_increment
        if self.x_offset > 0.7:
            self.x_increment = -self.x_increment
        gl.glProgramUniform1f(self.program.program_id, 0, self.x_offset)
        gl.glProgramUniform3f(self.program.program_id, 1, self.color[0], 
                              self.color[1], self.color[2])
        self.vao.bind()
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)

    # 释放资源
    def cleanup(self) -> None:
        self.vbo.delete()
        self.vao.delete()
        self.program.delete()

if __name__ == "__main__":
    app = TriangleApp(100, 100, 800, 600, "你好，三角形App！")
    app.run()

